import requests
import random
from fake_useragent import UserAgent
from urllib.parse import quote

class Tieba:
    def __init__(self):
        UA = UserAgent().random
        raw_cookie = 'BIDUPSID=4532E11B06AC72C13AA3E9B62B0D49A0; PSTM=1692089322; BAIDUID=4532E11B06AC72C1BACFEFD2A02680FB:FG=1; BD_UPN=12314753; H_PS_PSSID=40305_40499_40446_40080; BAIDUID_BFESS=4532E11B06AC72C1BACFEFD2A02680FB:FG=1; ZFY=xyDupCaHXyyWbwOH6zLsQTus8LQm7Hnn5PxNrSWMC2Y:C; __bid_n=18f4b72e5ba11524f53c82; COOKIE_SESSION=313_4_9_9_8_11_0_0_9_6_1_2_375_15242999_64_0_1714957969_1714481961_1714957905%7C9%238660891_9_1714481953%7C3; BDRCVFR[bPTzwF-RsLY]=mk3SLVN4HKm; BA_HECTOR=0gag050lak058k20aga00421s9dv9s1j3jfa61s; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDUSS=4tcUc4bX5JfjBOYVVET3RuZks3STltb3NPangxdTZFdzFMR3Yxc2laMWZTbUZtRVFBQUFBJCQAAAAAAAAAAAEAAABMtJGivbKyu8fltcDA7s~IyfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF-9OWZfvTlmbn; BDUSS_BFESS=4tcUc4bX5JfjBOYVVET3RuZks3STltb3NPangxdTZFdzFMR3Yxc2laMWZTbUZtRVFBQUFBJCQAAAAAAAAAAAEAAABMtJGivbKyu8fltcDA7s~IyfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF-9OWZfvTlmbn'
        encode_cookie = quote(raw_cookie)  # 转义
        self.url = 'https://tieba.baidu.com/f?'
        self.headers = {
            'User-Agent': UA,
            'Cookie': encode_cookie
        }
    def send(self,params):
        res = requests.get(self.url,headers=self.headers,params=params)
        return res.text

    def save(self,page,con):
        with open(f'{page}.html','w',encoding='utf-8') as f:
            f.write(con)

    def run(self):
        kw = input("输入名字：")
        num = int(input("输入页数："))

        for page in range(num):
            params ={
                'ke':kw,
                'pn':page *50
        }
        data =self.send(params)
        self.save(page,data)

te = Tieba()
te.run()
